<?php
declare(strict_types=1);

namespace app\middleware;

use app\Util\JwtUtil;
use app\service\UserService;

/**
 * token验证
 * Class CheckToken
 * @package app\middleware
 */
class CheckToken
{
    public function handle($request, \Closure $next)
    {
        // 登录接口无须验证token
        $token = $request->header('x-token');
        // token丢失
        if(empty($token)){
            throw new \app\MyException(11101);
        }
        $payload = JwtUtil::decode(think_decrypt($token));
        if($payload === false || empty($payload->user_id) || empty($payload->login_time)){
            throw new \app\MyException(11101);
        }
        // token过期判断
        $token_during = config('system.user_login_time');
        if($payload->login_time < time() - $token_during){
            throw new \app\MyException(11102);
        }
        // 实时用户数据
        $user = UserService::getInfoById($payload->user_id);
        // 用户是否存在
        if(empty($user)){
            throw new \app\MyException(11104);
        }
        // 是否多设备登录
        if(!empty($user['login_time']) && $user['login_time'] != $payload->login_time){
            throw new \app\MyException(11103);
        }
        // 用户状态
        if($user['disabled']){
            throw new \app\MyException(11106);
        }
        $request->sys_user = $user;
        return $next($request);
    }
}